import { SCREEN_WIDTH, SCREEN_HEIGHT } from '../render';

export default class Table {
  constructor() {
    this.margin = 30;
    this.left = this.margin;
    this.right = SCREEN_WIDTH - this.margin;
    this.top = this.margin + 40; // 上方多留点UI空间
    this.bottom = SCREEN_HEIGHT - this.margin;

    const pr = 14; // 袋口半径
    // 将中袋设置在左右长边的中点
    const cy = (this.top + this.bottom) / 2;

    // 四角 + 左右中袋（共6个）
    this.pockets = [
      { x: this.left,  y: this.top,    r: pr },  // 左上
      { x: this.right, y: this.top,    r: pr },  // 右上
      { x: this.left,  y: cy,          r: pr },  // 左侧中袋
      { x: this.right, y: cy,          r: pr },  // 右侧中袋
      { x: this.left,  y: this.bottom, r: pr },  // 左下
      { x: this.right, y: this.bottom, r: pr }   // 右下
    ];
  }

  getHeadStringPosition() {
    // 发球区靠近下边中间
    return { x: (this.left + this.right) / 2, y: this.bottom - 70 };
  }

  resolveWallCollision(ball) {
    // 左右边界
    if (ball.x - ball.r < this.left) {
      ball.x = this.left + ball.r;
      ball.vx = Math.abs(ball.vx) * 0.95;
    } else if (ball.x + ball.r > this.right) {
      ball.x = this.right - ball.r;
      ball.vx = -Math.abs(ball.vx) * 0.95;
    }

    // 上下边界
    if (ball.y - ball.r < this.top) {
      ball.y = this.top + ball.r;
      ball.vy = Math.abs(ball.vy) * 0.95;
    } else if (ball.y + ball.r > this.bottom) {
      ball.y = this.bottom - ball.r;
      ball.vy = -Math.abs(ball.vy) * 0.95;
    }
  }

  checkPocket(ball) {
    for (const p of this.pockets) {
      const dx = ball.x - p.x;
      const dy = ball.y - p.y;
      const dist2 = dx * dx + dy * dy;
      if (dist2 <= (p.r - ball.r * 0.2) * (p.r - ball.r * 0.2)) {
        return p;
      }
    }
    return null;
  }

  render(ctx) {
    // 台面背景
    ctx.save();
    ctx.fillStyle = '#0b6e34'; // 绿色台呢
    ctx.fillRect(this.left, this.top, this.right - this.left, this.bottom - this.top);

    // 边框
    ctx.strokeStyle = '#345';
    ctx.lineWidth = 8;
    ctx.strokeRect(this.left - 4, this.top - 4, this.right - this.left + 8, this.bottom - this.top + 8);

    // 袋口
    for (const p of this.pockets) {
      ctx.beginPath();
      ctx.fillStyle = '#222';
      ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2);
      ctx.fill();
    }

    ctx.restore();
  }
}